package com.sicilin.system.user.service;

import com.sicilin.common.exception.BusinessException;
import com.sicilin.common.exception.ServiceException;
import com.sicilin.common.page.PageObject;
import com.sicilin.common.page.PageUtils;
import com.sicilin.dao.UserDao;
import com.sicilin.po.TSysUser;
import com.sicilin.system.user.Admin;
import com.sicilin.system.user.dto.User;
import com.sicilin.system.user.util.UserUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(propagation = Propagation.REQUIRED,readOnly = true)
public class UserService {

    @Autowired(required = false)
    private UserDao userDao;

    @Autowired
    private Admin admin;

    @Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
    public TSysUser saveUser(String account,String name,String password,String telephone,int sex,int companyid,String email,String qq,String address) throws ServiceException,BusinessException{
        TSysUser user = new TSysUser();
        user.setAccount(account);
        user.setName(name);
        user.setPassword(password);
        user.setTelephone(StringUtils.isBlank(telephone) ? null : telephone);
        user.setSex(sex);
        user.setEmail(email);
        user.setQq(qq);
        user.setAddress(address);
        user.setStatus(1);
        user.setCompanyId(companyid);
        if(!UserUtils.validUpdateUser(user)){
            throw new BusinessException("添加的用户数据校验失败，请检查！");
        }
        if(this.isExistAccount(account)){throw new BusinessException("账号"+account+"已存在！");}
        if(this.isExistName(name)){throw new BusinessException("账号名称"+name+"已存在！");}
        userDao.saveUser(user);
        return user;
    }

    public boolean isExistName(String name) throws ServiceException{
        if(StringUtils.isBlank(name)){throw new ServiceException("Invalid name!");}
        if(userDao.existName(name) > 0){
            return true;
        }
        return false;
    }

    public boolean isExistAccount(String account) throws ServiceException{
        if(StringUtils.isBlank(account)){throw new ServiceException("Invalid account!");}
        if(userDao.existAccount(account) > 0){
            return true;
        }
        return false;
    }

    public boolean isExistsUser(String account,String password,int status)throws ServiceException{
        if(StringUtils.isBlank(account)){throw new ServiceException("Invalid account!");}
        if(StringUtils.isBlank(password)){throw new ServiceException("Invalid password!");}

        if("admin".equals(account) && admin.getPassword().equals(password)){
            return true;
        }

        if(userDao.existUser(account,password,status) > 0){
            return true;
        }
        return false;
    }

    public PageObject<User> searchUserWithPage(PageObject<User> pageObject, String searchText,int companyId) throws ServiceException{
        if(pageObject == null){throw new ServiceException("PageObject is null!");}
        pageObject.setTotal(userDao.countSearchUser(searchText,companyId));
        List<User> userList = userDao.searchUserLimit(searchText, PageUtils.getNumberStart(pageObject),pageObject.getRows(),companyId);
        pageObject.setRowsList(userList);
        return pageObject;
    }

    @Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
    public User updateUser(User user)throws ServiceException,BusinessException{
        if(user == null || user.getUserId() == null){throw new ServiceException("Invalid User or userId!");}
        User updateUser = userDao.findUserbyId(user.getUserId());
        if(updateUser == null){throw new BusinessException("需要修改的用户不存在!");}
        if(!updateUser.getAccount().equals(user.getAccount())) {
            if (this.isExistAccount(user.getAccount())) {
                throw new BusinessException("账号" + user.getAccount() + "已存在！");
            }
        }
        if(!updateUser.getName().equals(user.getName())){
            if (this.isExistName(user.getName())){
                throw new BusinessException("账号名称"+user.getName()+"已存在!");
            }
        }

        if(!UserUtils.validUpdateUser(user)){
            throw new BusinessException("修改的用户数据校验失败，请检查！");
        }
        user.setTelephone(StringUtils.isBlank(user.getTelephone()) ? null : user.getTelephone());
        userDao.updateUser(user);
        return user;
    }


    @Transactional(rollbackFor = {Exception.class})
    public int enableUser(int userId,int companyid) throws ServiceException{
        return userDao.updateStatus(userId,1,companyid);
    }

    @Transactional(rollbackFor = {Exception.class})
    public int disableUser(int userId,int companyid) throws ServiceException{
        return userDao.updateStatus(userId,0,companyid);
    }


}
